

import { useState } from "react";

function ToDoList() {
  const [tasks, setTasks] = useState(["Eat breakfast", "Take a Show"]);
  const [newTask, setNewTask] = useState("");

/**=============handle function============================== */
  const handleInputChange = (e) => setNewTask(e.target.value);
  const handleAddTask = () => {
    if (newTask.trim() !== "") {
      setTasks((t) => [...t, newTask]);
      setNewTask("");
    }
  };

  const handleDeleteTask = (index) => {
    setTasks((t) => t.filter((_, i) => i !== index));
  };

  const handleMoveUp = (index) => {
    if (index > 0) {
      const updateTasks = [...tasks];
      console.log(updateTasks);
      // 交换两个数组
      [updateTasks[index - 1], updateTasks[index]] = [
        updateTasks[index],
        updateTasks[index - 1],
      ];

      setTasks(updateTasks);
    }
  };

  const handleMoveDown = (index) => {
    if (index < tasks.length - 1) {
      const updateTasks = [...tasks];
      // 交换两个数组
      [updateTasks[index], updateTasks[index + 1]] = [
        updateTasks[index + 1],
        updateTasks[index],
      ];

      setTasks(updateTasks);
    }
  };
/**=======================list items===================================== */
  const listItems = tasks.map((task, index) => (
    <li key={index}>
      <span className="text">{task}</span>
      <button
        className="delete-btn btn"
        onClick={() => handleDeleteTask(index)}
      >
        Delete
      </button>
      <button className="move-btn btn" onClick={() => handleMoveUp(index)}>
        ⬆️
      </button>
      <button className="move-btn btn" onClick={() => handleMoveDown(index)}>
        ⬇️
      </button>
    </li>
  ));
/**===============================html structure=========================================== */
  return (
    <div className="to-do-list__container">
      <h1>To Do List</h1>
      <div>
        <input
          type="text"
          value={newTask}
          placeholder="Enter a task"
          onChange={handleInputChange}
        />
        <button className=" add-btn btn" onClick={handleAddTask}>
          Add
        </button>
      </div>
      <ol>{listItems}</ol>
    </div>
  );
}

export default ToDoList;
